    //
    //  FindPasswordViewController.m
    //  Kids
    //
    //  Created by LiTengFei on 14/12/12.
    //  Copyright (c) 2014年 90's Technology Co.Ltd. All rights reserved.
    //

#import "FindPasswordViewController.h"
#import "ChangePwdTableViewCell.h"


#import "FindPasswordRequestData.h"
#import "FindPasswordResponseData.h"
#import "RequestFactory.h"
#import "UIColor+Extend.h"

#import "VerificationCodeRequestData.h"
#import "VerificationCodeResponseData.h"
#import "SVProgressHUD.h"
#import "AccountInfo.h"


#define  NSIndexPathMake(_M_,_N_) [NSIndexPath indexPathForRow:_M_ inSection:_N_]

@interface FindPasswordViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UIScrollView * backView;

@property (nonatomic,strong) UILabel * phoneLabel;
@property (nonatomic,strong) UITextField * phoneField;

@property (nonatomic,strong) UILabel * nowPasswordLabel;
@property (nonatomic,strong) UITextField * nowPasswordField;

@property (nonatomic,strong) UILabel * confirmPasswordLabel;
@property (nonatomic,strong) UITextField * confirmPasswordField;

@property (nonatomic,strong) UIButton * submitButton;

@property (nonatomic,strong) UIButton * getCodeBtn;
@property (nonatomic,strong) UITextField * codeTextField;

@property (nonatomic,assign) NSInteger timerCount;
@end


@implementation FindPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"忘记密码";
    CGRect frame = [[UIScreen mainScreen]bounds];
    self.view.backgroundColor = [UIColor colorF2F2F2];
    self.backView = [[UIScrollView alloc]initWithFrame:frame];
    self.backView.backgroundColor = [UIColor colorF2F2F2];
    self.backView.scrollEnabled = YES;
    
    UIView * passwordBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, CGRectGetWidth(frame), 120)];
    passwordBackView.backgroundColor = [UIColor whiteColor];
    
    self.phoneLabel=({
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 100, 30)];
        label.text = @"当前手机号";
        label;
    });
    [passwordBackView addSubview:self.phoneLabel];
    self.phoneField=({
        UITextField * field = [[UITextField alloc]initWithFrame:CGRectMake(120, 5, 180, 30)];
        field.textAlignment = NSTextAlignmentRight;
        field.delegate =self;
        field.keyboardType = UIKeyboardTypeASCIICapable;
        field.returnKeyType = UIReturnKeyDone;
        field;
    });
    [passwordBackView addSubview:self.phoneField];
    [passwordBackView addSubview:singleLineWithRect(CGRectMake(0, 40, CGRectGetWidth(frame), 0.5))];
    
    self.nowPasswordLabel=({
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 45, 100, 30)];
        label.text = @"新密码";
        label;
    });
    [passwordBackView addSubview:self.nowPasswordLabel];
    self.nowPasswordField=({
        UITextField * field = [[UITextField alloc]initWithFrame:CGRectMake(120, 45, 180, 30)];
        field.textAlignment = NSTextAlignmentRight;
        field.secureTextEntry = YES;
        field.keyboardType = UIKeyboardTypeASCIICapable;
        field.returnKeyType = UIReturnKeyDone;
        field.delegate =self;
        field;
    });
    [passwordBackView addSubview:self.nowPasswordField];
    [passwordBackView addSubview:singleLineWithRect(CGRectMake(0, 40, CGRectGetWidth(frame), 0.5))];
    
    
    self.confirmPasswordLabel=({
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 85, 100, 30)];
        label.text = @"确认密码";
        label;
    });
    [passwordBackView addSubview:self.confirmPasswordLabel];
    self.confirmPasswordField=({
        UITextField * field = [[UITextField alloc]initWithFrame:CGRectMake(120, 85, 180, 30)];
        field.textAlignment = NSTextAlignmentRight;
        field.secureTextEntry = YES;
        field.keyboardType = UIKeyboardTypeASCIICapable;
        field.returnKeyType = UIReturnKeyDone;
        field.delegate =self;
        field;
    });
    [passwordBackView addSubview:self.confirmPasswordField];
    [passwordBackView addSubview:singleLineWithRect(CGRectMake(0, 80, CGRectGetWidth(frame), 0.5))];
    
    UIView * submitBackgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 200, CGRectGetWidth(frame), 100)];
    submitBackgroundView.backgroundColor = [UIColor whiteColor];
    
    self.getCodeBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    self.getCodeBtn.frame =CGRectMake(25, 5, 100, 38);
    self.getCodeBtn.adjustsImageWhenDisabled = YES;
    [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.getCodeBtn setBackgroundImage:[UIImage imageNamed:@"yellow1"] forState:UIControlStateNormal];
    [self.getCodeBtn setBackgroundImage:[UIImage imageNamed:@"yellow1_press"] forState:UIControlStateHighlighted];
    [self.getCodeBtn addTarget:self action:@selector(getCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [submitBackgroundView addSubview:self.getCodeBtn];
    
    UIImageView * codeBackground = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"gray1"]];
    codeBackground.frame =CGRectMake(130, 5, 129, 40);
    [submitBackgroundView addSubview:codeBackground];
    
    self.codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(140, 5, 110, 40)];
    self.codeTextField.placeholder = @"输入验证码";
    self.codeTextField.returnKeyType = UIReturnKeyDone;
    self.codeTextField.keyboardType = UIKeyboardTypeASCIICapable;
    self.codeTextField.returnKeyType = UIReturnKeyDone;
    self.codeTextField.delegate = self;
    [submitBackgroundView addSubview:self.codeTextField];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 50, 100, 38);
    button.center = CGPointMake(CGRectGetWidth(frame) / 2, 75);
    [button setTitle:@"确认提交" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"yellow"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"yellow_press"] forState:UIControlStateHighlighted];
    
    [button addTarget:self action:@selector(submitClick:) forControlEvents:UIControlEventTouchUpInside];
    [submitBackgroundView addSubview:button];
    
    [self.backView addSubview:passwordBackView];
    [self.backView addSubview:submitBackgroundView];
    [self.view addSubview:self.backView];
    
    NSNotificationCenter * notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(notificationShow:) name:UIKeyboardWillShowNotification object:nil];
    [notification addObserver:self selector:@selector(notificationHide:) name:UIKeyboardWillHideNotification object:nil];
    
    self.navigationItem.rightBarButtonItem = ({
        UIButton  * button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [button setTitle:@"关闭" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(returnClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * returnButton = [[UIBarButtonItem alloc]initWithCustomView:button];
        returnButton;
    });
    
   
}
-(void)returnClick:(UIBarButtonItem *)barbutton{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)notificationShow:(NSNotification *)notification{
    CGRect frame =  [[UIScreen mainScreen]bounds];
    if([self.codeTextField isFirstResponder]){
        [UIView animateWithDuration:0.5 animations:^{
            self.backView.frame = CGRectMake(0, -150, CGRectGetWidth(frame), CGRectGetHeight(frame));
        }];
    }
}
-(void)notificationHide:(NSNotification *)notification{
    CGRect frame = [[UIScreen mainScreen]bounds];
    self.backView.frame = frame;
}
    //-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //    if([textField isEqual:self.codeTextField]){
    //        CGPoint point = self.codeTextField.superview.frame.origin;
    //        self.backView.contentOffset = CGPointMake(point.x, point.y);
    //    }
    //    return YES;
    //}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark -
- (void)getCodeBtnClick:(UIButton *)button {
    NSString * phone =  self.phoneField.text;
    if ([self isValidateMobile:phone]) {
        VerificationCodeRequestData *request = [[VerificationCodeRequestData alloc] init];
        request.phone = phone;
        
        VerificationCodeResponseData *response = [[VerificationCodeResponseData alloc] init];
        [RequestFactory requestWithRequestData:request forResponseData:response complete:^(ResponseData *responseData, NSError *error) {
            if (responseData) {
                VerificationCodeResponseData *response = (VerificationCodeResponseData *)responseData;
                if (response.result == 1) {
                    [self startTimer];
                    [SVProgressHUD showSuccessWithStatus:@"验证码发送成功!"];
                }else {
                    [SVProgressHUD showErrorWithStatus:response.info];
                }
            }else{
                NSLog(@"error %@",error.localizedDescription);
            }
        }];
    } else {
        [SVProgressHUD showErrorWithStatus:@"请输入格式正确的手机号！"];
    }
}
- (BOOL)isValidateMobile:(NSString*)mobile
{
        //手机号以13， 15，18开头，八个 \d 数字字符
    NSString* phoneRegex = @"^[1][3578]\\d{9}$";
    NSPredicate* phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}

- (void)startTimer {
    self.timerCount = 60;
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
    [self disableCodeButton];
}
- (void)stopTimer:(NSTimer *)timer
{
    [timer invalidate];
    self.timerCount = 0;
    [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self enableCodeButton];
}
- (void)disableCodeButton {
    [self.getCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.getCodeBtn.enabled = NO;
    self.getCodeBtn.userInteractionEnabled = NO;
}

- (void)enableCodeButton
{
    [self.getCodeBtn setTitle:@"重新获取(60)" forState:UIControlStateNormal];
    self.getCodeBtn.userInteractionEnabled = YES;
    self.getCodeBtn.enabled = YES;
}

- (void)onTimer:(NSTimer *)timer
{
    self.timerCount--;
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"重新获取(%ld)", (unsigned long)self.timerCount] forState:UIControlStateNormal];
    if (self.timerCount <= 0) {
        [self stopTimer:timer];
    }
}


- (void)submitClick:(UIButton *)button {
    NSString * mobilePhone = self.phoneField.text;
    NSString * nowPassword = self.nowPasswordField.text;
    NSString * confirmPawword = self.confirmPasswordField.text;
    if (!mobilePhone ||mobilePhone.length == 0) {
        [SVProgressHUD showImage:nil status:@"请输入手机号码"];
        return;
    }else  if (!nowPassword || nowPassword.length == 0) {
        [SVProgressHUD showImage:nil status:@"请输入密码"];
        return;
    }else if (!confirmPawword || confirmPawword.length == 0) {
        [SVProgressHUD showImage:nil status:@"请输入确认密码"];
        return;
    }else if(self.codeTextField.text.length == 0){
            [SVProgressHUD showImage:nil status:@"输入验证码"];
            return;
    }
    NSParameterAssert(mobilePhone.length>0);
    NSParameterAssert(nowPassword.length>0);
    NSParameterAssert(confirmPawword.length>0);
    NSParameterAssert(self.codeTextField.text.length>0);
    
    FindPasswordRequestData * request = [[FindPasswordRequestData alloc]init];
    request.phone = mobilePhone;
    request.passwordNew = nowPassword;
    request.verifyCode = self.codeTextField.text;
    
    [RequestFactory requestWithRequestData:request forResponseData:[FindPasswordResponseData new] complete:^(ResponseData *responseData, NSError *error) {
        FindPasswordResponseData * data = (FindPasswordResponseData *)responseData;
        if (data.result == 1) {
            [[AccountInfo shareInstance] setLoginState:LoginStateOnline];
            [[AccountInfo shareInstance] setPhone:mobilePhone];
            [[AccountInfo shareInstance] setPassword:nowPassword];
            
            [self jumpToHomeViewController];
        }
        else {
            [SVProgressHUD showErrorWithStatus:data.info];
        }
        NSLog(@"%@",data.info);
    }];
}

-(void)jumpToHomeViewController{
    UIStoryboard * storeBoard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    
    UINavigationController * controller = [storeBoard instantiateViewControllerWithIdentifier:@"mainViewController"];
    
    
    [UIApplication sharedApplication].keyWindow.rootViewController = controller;
}

@end
